package com.gk.javaservice.controller;

import com.alibaba.fastjson.JSONObject;
import com.gk.javaservice.common.ServerResponse;
import com.gk.javaservice.util.javaRequest.HttpUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/ServerIp")
public class ServerIpController {


    private Logger log = Logger.getLogger(this.getClass());


    //http://192.168.10.112:9090/task/add
    @CrossOrigin
    @ResponseBody
    @RequestMapping("/ServerRequest")
    public ServerResponse<?> ServerRequest(@RequestBody JSONObject para) {
        log.info("in to ServerRequest:");
        JSONObject json = para.getJSONObject("value");
        String ip = para.getString("ip");
        String port = para.getString("port");
        String path = para.getString("path");
        String url = "http://" + ip + ":" + port + path;
        log.info("url:" + url);
        JSONObject msg = HttpUtil.doPost(url, json);
        log.info(msg);
        return ServerResponse.createBySuccess(msg);

    }


    @CrossOrigin
    @ResponseBody
    @RequestMapping("/getip")
    public ServerResponse<?> getIp(final HttpServletRequest request) {
        String ip = request.getHeader("X-FORWARDED-FOR");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ServerResponse.createBySuccess(ip);
    }
}
